package com.company.huisuo.base

import android.graphics.Rect
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import com.company.huisuo.ext.hideKeyboard
import com.company.huisuo.utils.StatusBarUtil
import com.company.huisuo.utils.TaskManager.addTask
import com.company.huisuo.utils.TaskManager.removeTask
import com.company.huisuo.widget.LoadingView
import java.lang.reflect.ParameterizedType

@Suppress("UNCHECKED_CAST")
abstract class BaseActivity<VB : ViewBinding> : AppCompatActivity() {

    private val _binding by lazy {
        buildViewBinding()
    }
    private val _loadingView by lazy {
        LoadingView(this).apply {
            setCanceledOnTouchOutside(false)
        }
    }

    // 是否允许点击EditText外部隐藏软键盘，默认允许
    private var _isKeyboardHideOnTouchOutside = true

    val mBinding: VB
        get() = _binding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(_binding.root)

        this.addTask()
        StatusBarUtil.immersiveStatusBar(this)
        initView()
        initData()
        observerData()
    }

    override fun onDestroy() {
        super.onDestroy()
        this.removeTask()
        dismissLoading()
    }

    abstract fun initView()

    abstract fun initData()

    private fun observerData() {

    }

    private fun buildViewBinding(): VB {
        val superClass = javaClass.genericSuperclass as ParameterizedType
        val vbClass = superClass.actualTypeArguments[0] as Class<VB>
        val method = vbClass.getMethod("inflate", LayoutInflater::class.java)
        return method.invoke(null, layoutInflater) as VB
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (event?.action == MotionEvent.ACTION_DOWN) {
            val view = currentFocus
            if (view is EditText) {
                val outRect = Rect()
                view.getGlobalVisibleRect(outRect)
                if (!outRect.contains(event.rawX.toInt(), event.rawY.toInt())) {
                    if (_isKeyboardHideOnTouchOutside) {
                        hideKeyboard()
                    }
                }
            }
        }
        return super.onTouchEvent(event)
    }

    /**
     * 是否允许点击EditText外部隐藏软键盘
     */
    open fun allowKeyboardHideOnTouchOutside(flag: Boolean) {
        _isKeyboardHideOnTouchOutside = flag
    }

    /**
     * 显示Loading
     */
    fun showLoading() {
        _loadingView.show()
    }

    /**
     * 隐藏Loading
     */
    fun dismissLoading() {
        _loadingView.dismiss()
    }
}